export function createSingle(obj: any, key: string) {
  if (!(window as any)[`__${key}`]) {
    (window as any)[`__${key}`] = obj;
  }
  return (window as any)[`__${key}`];
}

export const fetchTransformStream = (res, resolve) => {
  const transformStream = new TransformStream();
  const reader = res.body.getReader();
  const writer = transformStream.writable.getWriter();
  function readStream() {
    reader.read().then(function processText({ done, value }) {
      if (done) {
        writer.write(value);
        writer.close();
        console.log("Stream complete");
        return;
      }
      const value2 = new TextDecoder().decode(value);
      const str = value2
        .split("\n")
        .map((str) => {
          const text = str.substring(5, str.length);
          console.log("text", text);
          if (text) {
            const json = JSON.parse(text);
            if (json.text) {
              json.text = json.text + "模拟-";
            }
            return `data: ${JSON.stringify(json)}`;
          }

          return str;
        })
        .join("\n");

      writer.write(Buffer.from(str));

      // 继续读取
      readStream();
    });
  }
  readStream();

  resolve(
    new Response(transformStream.readable, {
      headers: res.headers,
      status: res.status,
      statusText: res.statusText,
    })
  );
};
